package apiroute

import (
	"git.sr.ht/~mil/mobroute/src/db"
	"time"
)

func walksToMapTimeSecs(walks *[]db.StopWalk, walkspeedKmHr float64) map[string]uint {
	walkTimesMap := map[string]uint{}
	for _, w := range *walks {
		if w.DistKM == nil {
			// E.g. distance exceeded max walk km, just return an arbitrarily
			// large sized constant (sized to 7 days); this is preferable for now to
			// manually flagging a nil value in csa algorithm downstram which would
			// require excess nil checking in constrast to just gt/lt checks
			walkTimesMap[w.StopSIDU] = 60 * 60 * 24 * 7
		} else {
			walkTimesMap[w.StopSIDU] = walkCalcSecs(*w.DistKM, walkspeedKmHr)
		}
	}
	return walkTimesMap
}

func countNonNilWalks(walks *[]db.StopWalk) int {
	n := 0
	for _, w := range *walks {
		if w.DistKM != nil {
			n += 1
		}
	}
	return n
}

// walkCalcSecs calculates the seconds it takes to walk the given distKm given
func walkCalcSecs(distKm, walkspeedKmHr float64) uint {
	return uint(distKm / walkspeedKmHr * 60 * 60)
}

// walkKmInSecondsGivenKmHr calculate the number of km that can be walked
// for walkSeconds given the rate of walkspeedKmHr
func walkKmInSecondsGivenKmHr(walkSeconds uint, walkspeedKmHr float64) float64 {
	return walkspeedKmHr / 60 / 60 * float64(walkSeconds)
}

func ptr[T any](a T) *T {
	return &a
}

func coalesce[T any](a, b *T) *T {
	if a != nil {
		return a
	} else {
		return b
	}
}

type Timer struct {
	lastTime time.Time
}

func (t *Timer) Snapshot() string {
	now := time.Now()
	delta := now.Sub(t.lastTime)
	t.lastTime = now
	return delta.String()
}
